<template>
  <div class="app-container">
    <el-row >
        <el-form :model="messageList"  label-width="68px">
          <el-col :span="6">
            <el-form-item label="所属机构" prop="type">
              <treeselect v-model="queryParams.type" :options="deptList" :show-count="true" placeholder="请选择所属机构" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="-5">
            <el-form-item label="安全制度分类名称" prop="classifyName" size="small" label-width="150px">
              <el-input v-model="queryParams.classifyName" ></el-input>              
            </el-form-item>
          </el-col>
          <el-col :span="5" >
            <el-form-item label="状态" prop="state"  size="small">
              <el-select v-model="queryParams.state" placeholder="请选择">
              <el-option label="正常" value=2></el-option>
              <el-option label="停用" value=1></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-button icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-col>
       </el-form>
    </el-row>
    <el-row  :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd" >新建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>
    <!-- 显示列表 -->
    <el-row>
      <el-col >
        <el-table v-loading="loading" :data="messageList" stripe @selection-change="handleSelectionChange">
          <el-table-column type="index" width="55" align="center" />
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="sysDept.deptName"
            label="所属机构"
            sortable
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            prop="number"
            label="编号"
            sortable
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            prop="classifyName"
            label="分类名称"
            sortable
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
          prop="state"
             label="状态"
            sortable
            align="center"
            width="200"
            >
            <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.state==2">正常</el-tag>
                <el-tag type="danger" v-if="scope.row.state==1">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row.id)">编辑</el-button>
            </template>
          </el-table-column>

        </el-table>
        <pagination 
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <!-- 新增/编辑弹框 -->
      <el-dialog :title="title" :visible.sync="open"  width="600px">
        <el-form label-width="100px" :model="form" :rules="rules" ref="form1" :label-position="labelPosition">
          <el-form-item label="编号" prop="number">
            <el-input v-model="form.number"></el-input>
          </el-form-item>
          <el-form-item label="分类名称" prop="classifyName">
            <el-input v-model="form.classifyName"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
              <el-radio label=2 v-model="form.state" >正常</el-radio>
              <el-radio label=1 v-model="form.state" >停用</el-radio>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    </el-row>
    
  </div>


</template>

<script>
import {listMessage,addSafeClassify,getMessageById,getDeptList,delUser} from "@/api/system/safeClassify";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      //左对齐
      labelPosition: 'left',
      //安全分类表格数据
      messageList: null,
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //所属机构
      deptList: undefined,
      // 机构id
      deptId: undefined,
       // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

      },
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      form1: {
        number: '',
        classifyName: '',
        state: '',
      },
      // form 表单校验
      rules: {
        number: [
          { required: true, message: '请输入编号', trigger: 'blur' },
        ],
        classifyName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
        state: [
          { required: true,message: '请选择状态'}
        ]
      },
      // 选中数据id
      ids: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/aqsc/safeClassify/importData"
      },
    };
  },

  mounted(){
    this.getList()
    this.getDeptTree()

  },
  methods:{
     /** 查询所属机构下拉树结构 */
    getDeptTree() {
      getDeptList().then(response => {
        this.deptList = response.data;
      });
    },
    //列表查询
    getList(){
      listMessage(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.loading=true;
        this.messageList = response.rows;
        this.total = response.total;
        this.loading = false;  
       
        }
      )
    },
    /** 查询按钮操作 */
    handleQuery() {
      console.info(this.form)
      this.queryParams.pageNum = 1; 
      this.getList();
    },
    //重置
    resetQuery(){
      this.form = {}
      this.queryParams = {}
      this.queryParams.pageNum = 1; 
      this.getList()
    },
    //新增信息
    handleAdd() {
      if(this.queryParams.type!=undefined){
        this.form={}
        this.open = true
        this.title = "新建"
        this.form.type = this.queryParams.type
      }else{
        this.$alert('请选择所属机构', {
          confirmButtonText: '确定',
        });
      }   

    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      getMessageById(id).then(response => {
        console.info(id)
        this.form = response;
        this.open = true;
        this.title = "编辑用户";
      });
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //取消
    cancel(){
      this.open = false
      this.form = {}
    },
    //提交
    submitForm(){   
       this.$refs['form1'].validate((valid) => {
          if (valid) {
            addSafeClassify(this.form).then(resp=> {
              if (resp.result) {
                this.$message(resp.msg) //弹出成功
              }    
              this.open = false
              this.queryParams.type = null
              this.queryParams.classifyName = null
              this.queryParams.state = null
              this.getList()
              this.form = {}              
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      
    },
      /** 导出按钮操作 */
    handleExport() {
      this.download('aqsc/safeClassify/export', {
        ...this.queryParams
      }, `safeClassify_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('aqsc/safeClassify/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
